/**
 * 导航RAG管理API接口
 */

import axios from 'axios'

// 基础配置 - 统一使用vite代理配置
const API_BASE_URL = '/api'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    console.log('Navigation API Request:', config.method?.toUpperCase(), config.url)
    return config
  },
  (error) => {
    console.error('Navigation Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    console.log('Navigation API Response:', response.status, response.config.url)
    return response.data
  },
  (error) => {
    console.error('Navigation Response Error:', error.response?.status, error.config?.url, error.response?.data)
    return Promise.reject(error)
  }
)

// 过滤空参数的工具函数
const filterEmptyParams = (params?: Record<string, any>) => {
  if (!params) return {}
  return Object.fromEntries(
    Object.entries(params).filter(([_, value]) => 
      value !== null && value !== undefined && value !== ''
    )
  )
}

// 类型定义
export interface NavigationData {
  page_id: string
  scene_id: string
  tenant_id: string
  page_name: string
  page_tab: string[]
  function_desc_list: string[]
  operation_desc_list: string[]
  navigation_path: string
  prev_path_list: string[]
  next_path_list: string[]
  mcp_list: string[]
  is_deleted: number
  created_by: string
  created_at: string
  updated_by?: string
  updated_at?: string
}

export interface NavigationSearchParams {
  page_name?: string
  navigation_path?: string
  scene_id?: string
  tenant_id?: string
  created_by?: string
  page_num?: number
  page_size?: number
}

export interface NavigationListResponse {
  code: number
  message: string
  data: {
    items: NavigationData[]
    total: number
    page_num: number
    page_size: number
  }
}

export interface NavigationCreateRequest {
  page_name: string
  navigation_path: string
  scene_id: string
  tenant_id: string
  page_tab: string[]
  function_desc_list: string[]
  operation_desc_list: string[]
  prev_path_list: string[]
  next_path_list: string[]
  mcp_list: string[]
  created_by: string
}

export interface NavigationUpdateRequest {
  page_name?: string
  navigation_path?: string
  scene_id?: string
  tenant_id?: string
  page_tab?: string[]
  function_desc_list?: string[]
  operation_desc_list?: string[]
  prev_path_list?: string[]
  next_path_list?: string[]
  mcp_list?: string[]
  updated_by: string
}

export interface NavigationResponse {
  code: number
  message: string
  data: NavigationData
}

export interface ImportResponse {
  code: number
  message: string
  data: {
    success_count: number
    error_count: number
    errors?: string[]
  }
}

export interface DeleteResponse {
  code: number
  message: string
  data: {
    message: string
    success_count?: number
    failed_count?: number
    failed_ids?: string[]
  }
}

// 导航RAG相关API
export const navigationApi = {
  // 获取导航列表
  getList: (params?: NavigationSearchParams): Promise<NavigationListResponse> => {
    const queryParams = new URLSearchParams()
    
    if (params) {
      Object.entries(filterEmptyParams(params)).forEach(([key, value]) => {
        queryParams.append(key, String(value))
      })
    }
    
    return apiClient.get(`/navigation/list?${queryParams.toString()}`)
  },

  // 创建导航
  create: (data: NavigationCreateRequest): Promise<NavigationResponse> => 
    apiClient.post('/navigation/create', data),

  // 根据ID获取导航详情
  getById: (pageId: string): Promise<NavigationResponse> => 
    apiClient.get(`/navigation/${pageId}`),

  // 更新导航
  update: (pageId: string, data: NavigationUpdateRequest): Promise<NavigationResponse> => 
    apiClient.put(`/navigation/${pageId}`, data),

  // 删除导航
  delete: (pageId: string, updatedBy: string): Promise<DeleteResponse> => {
    const params = new URLSearchParams()
    params.append('updated_by', updatedBy)
    return apiClient.delete(`/navigation/${pageId}?${params.toString()}`)
  },

  // 批量删除导航
  batchDelete: (pageIds: string[], updatedBy: string): Promise<DeleteResponse> => {
    const requestBody = {
      page_ids: pageIds,
      updated_by: updatedBy
    }
    return apiClient.post('/navigation/batch/delete', requestBody)
  },

  // 导入Excel
  import: async (file: File, importMode: 'insert' | 'update' | 'upsert', createdBy: string): Promise<ImportResponse> => {
    const formData = new FormData()
    formData.append('file', file)
    
    const params = new URLSearchParams()
    params.append('import_mode', importMode)
    params.append('created_by', createdBy)
    
    const response = await fetch(`${API_BASE_URL}/navigation/import?${params.toString()}`, {
      method: 'POST',
      body: formData
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return response.json()
  },

  // 导出Excel
  export: async (filters?: { scene_ids?: string[], include_deleted?: boolean }): Promise<Blob> => {
    const requestBody = {
      scene_ids: filters?.scene_ids || null,
      include_deleted: filters?.include_deleted || false,
      export_format: "excel"  // 添加导出格式字段
    }
    
    const response = await fetch(`${API_BASE_URL}/navigation/export`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestBody)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return response.blob()
  },

  // 下载导入模板
  downloadTemplate: async (): Promise<Blob> => {
    const response = await fetch(`${API_BASE_URL}/navigation/template/download`)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return response.blob()
  }
}

export default apiClient
